package com.qosdroid;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
//import android.content.Intent;
//import android.net.Uri;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.*;
import android.telephony.gsm.GsmCellLocation;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
//import android.net.*;

/*import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;*/

public class QOSdroidActivity extends Activity {
    /** Called when the activity is first created. */
	String values;
	int myLatitude, myLongitude;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        String d, c, o, t, l1, l2;
        TableLayout layout = new TableLayout(this);
        TextView txt = new TextView(this);
        Button save = new Button(this);
        Button quit = new Button(this);
        save.setText("Save");
        quit.setText("Quit");

        /*ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        boolean online = ni.isAvailable();
        tv.setText("Online: " + online);*/

        TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        GsmCellLocation cellLocation = (GsmCellLocation) tm.getCellLocation();
        
        txt.setText("Welcome to QoSME (Quality of Service and Mobile Efficiency) nameless.ph/qosme\n\nThese values were read from your phone and cellular network. On Save, they will be sent to the server and may be provided to third parties. Thank you very much.\n\n");
        
        d = String.valueOf(tm.getDeviceId());
        txt.append("Device ID is " + d + ".\n");
        c = tm.getNetworkOperatorName();
        txt.append("Phone network is " + c + ".\n");
        switch (tm.getDataState()) {
	    	case 0:
	    		o = "Offline";
	    		break;
	    	case 1:
	    		o = "Connecting";
	    		break;
        	case 2:
        		o = "Connected";
        		break;
        	case 3:
        		o = "Suspended";
        		break;
        	default:
        		o = "in an Unknown State.\n";
        }
        txt.append("Data connection is " + o + ".\n");
        switch (tm.getNetworkType()) {
        	case 0: 
        		t = "Unknown";
        		break;
        	case 1: 
        		t= "GSM";
        		break;
        	case 2: 
        		t = "EDGE";
        		break;
        	case 3: 
        		t = "UMTS";
        		break;
        	case 4: 
        		t = "CDMA";
        		break;
        	case 5: 
        		t = "EVDO revision 0";
        		break;
        	case 6: 
        		t = "EVDO revision A";
        		break;
        	case 7: 
        		t = "1xRTT";
        		break;
        	case 8: 
        		t = "HSDPA";
        		break;
        	case 9: 
        		t = "HSUPA";
        		break;
        	case 10: 
        		t = "HSPA";
        		break;
        	case 11: 
        		t = "iDen";
        		break;
        	case 12: 
        		t = "EVDO revision B";
        		break;
        	case 13: 
        		t = "LTE";
        		break;
        	case 14: 
        		t = "eHRPD";
        		break;
        	case 15: 
        		t = "HSPA+";
        		break;
        	default: 
        		t = "Undetermined";
        }
        txt.append("Data connection type is " + t + ".\n");

        int cid = cellLocation.getCid();
        int lac = cellLocation.getLac();
        l1 = String.valueOf(cid);
        l2 = String.valueOf(lac);
       
        txt.append("Your location: cid " + l1 + ", lac " + l2 + ".\n");
        txt.append("Latitude : Longitude = ");
        String lon, lat;
        if (RqsLocation(cid, lac)) {
            lat = String.valueOf((float)myLatitude/1000000);
            lon = String.valueOf((float)myLongitude/1000000);
        	txt.append(lat + " : " + lon + ".\n");
        } else {
        	lat = "0.0";
        	lon = "0.0";
        	txt.append("Can't find Location!\n");
        }
        values = d + "," + c + "," + o + "," + t + "," + l1 + "," + l2 + "," + lat + "," + lon;
        //SignalStrength ss = (SignalStrength) this.getSystemService(Context.TELEPHONY_SERVICE);
        //txt.append(ss.toString());
        layout.addView(txt);
        layout.addView(save);
        layout.addView(quit);
        setContentView(layout);
        quit.setOnClickListener(new quitClickHandler());
        save.setOnClickListener(new saveClickHandler());
    }
    
    private Boolean RqsLocation(int cid, int lac){
 	   
 	   Boolean result = false;
 	 
 	   String urlmmap = "http://www.google.com/glm/mmap";
 	 
 	      try {
 	       URL url = new URL(urlmmap);
 	          URLConnection conn = url.openConnection();
 	          HttpURLConnection httpConn = (HttpURLConnection) conn;      
 	          httpConn.setRequestMethod("POST");
 	          httpConn.setDoOutput(true);
 	          httpConn.setDoInput(true);
 	  httpConn.connect();
 	  
 	  OutputStream outputStream = httpConn.getOutputStream();
 	        WriteData(outputStream, cid, lac);
 	       
 	        InputStream inputStream = httpConn.getInputStream();
 	        DataInputStream dataInputStream = new DataInputStream(inputStream);
 	       
 	        dataInputStream.readShort();
 	        dataInputStream.readByte();
 	        int code = dataInputStream.readInt();
 	        if (code == 0) {
 	         myLatitude = dataInputStream.readInt();
 	         myLongitude = dataInputStream.readInt();
 	           
 	            result = true;
 	           
 	        }
 	 } catch (IOException e) {
 	  // TODO Auto-generated catch block
 		 e.printStackTrace();
 	 }
 	 
 	 return result;
 	   
 	  }
 
	 private void WriteData(OutputStream out, int cid, int lac)
	 		  throws IOException		  
	 {    
	 	DataOutputStream dataOutputStream = new DataOutputStream(out);
	 	dataOutputStream.writeShort(21);
	 	dataOutputStream.writeLong(0);
	 	dataOutputStream.writeUTF("en");
	 	dataOutputStream.writeUTF("Android");
	 	dataOutputStream.writeUTF("1.0");
	 	dataOutputStream.writeUTF("Web");
	 	dataOutputStream.writeByte(27);
	 	dataOutputStream.writeInt(0);
	 	dataOutputStream.writeInt(0);
	 	dataOutputStream.writeInt(3);
	 	dataOutputStream.writeUTF("");
	 		 
	 	dataOutputStream.writeInt(cid);
	 	dataOutputStream.writeInt(lac);   
	 		 
	 	dataOutputStream.writeInt(0);
	 	dataOutputStream.writeInt(0);
	 	dataOutputStream.writeInt(0);
	 	dataOutputStream.writeInt(0);
	 	dataOutputStream.flush();    	
	 }

    private class quitClickHandler implements OnClickListener {
    	public void onClick (View arg0) {
    		finish();
    	}
    }
    private class saveClickHandler implements OnClickListener {
    	public void onClick (View arg0) {
    		Button b = (Button) arg0;
    		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://nameless.ph/qosme/post.php?values=" + values));
    		startActivity(intent);
    		b.setText("Saved");
    	}
    }
}
